import time

from loguru import logger
import pandas as pd
from read_search_file import get_search_comp, mock_click_js, get_complete_sheet1

def log_message(log_callback, message, color=None):
    if callable(log_callback):
        log_callback(message, color) if color else log_callback(message)


# def create_creative_func(creative_view_tab, r_excel, browser, file_path, unit_next_button_ele=None, log_callback=None, df_sheet=None):
#     # creative_view_tab.wait.load_start()
#     logger.info(f"进入创意界面")
#     creative_name = r_excel['创意名称']
#     img_all_select = r_excel['封面全选']
#
#     creative_view_tab.wait.eles_loaded('tag:input@@class=d-text@@type=text@@placeholder=请输入你的创意名称')  # 等待元素加载
#     creative_name_ele = creative_view_tab.ele('tag:input@@class=d-text@@type=text@@placeholder=请输入你的创意名称', timeout=5)
#
#     if not creative_name_ele:
#         if unit_next_button_ele:
#             unit_next_button_ele.click(by_js=True)
#             creative_name_ele = creative_view_tab.ele('tag:input@@class=d-text@@type=text@@placeholder=请输入你的创意名称', timeout=5)
#
#     creative_name_ele.input(creative_name, clear=True)  # 填写创意名称
#
#     monitor_link = r_excel['监测链接']
#     exposure_link = None
#
#     if '曝光链接' in df_sheet.columns:
#         exposure_link = r_excel['曝光链接']
#
#     indus_qualification = r_excel['行业资质']
#     auto_optimize = r_excel['自动优化'] if pd.notna(r_excel['自动优化']) else "关闭"
#     trans_comp = r_excel['转化组件'] if pd.notna(r_excel['转化组件']) else "无"
#
#     if pd.notna(monitor_link) or pd.notna(exposure_link):
#         if edit_monitor_link := creative_view_tab.ele('tag:div@@text()=修改监测链接', timeout=1):
#             creative_view_tab.wait(1)
#             edit_monitor_link.click(by_js=True, timeout=3)
#             if pd.notna(monitor_link):
#                 monitor_link = monitor_link.strip()
#                 creative_view_tab.ele('tag:span@@class=label-text@@text()=点击监测链接').parent(1).next().ele('tag:input@@class=d-text@@placeholder=请输入链接').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', monitor_link)  # 输入链接
#             if pd.notna(exposure_link):
#                 exposure_link = exposure_link.strip()
#                 creative_view_tab.ele('tag:span@@class=label-text@@text()=曝光监测链接').parent(1).next().ele('tag:input@@class=d-text@@placeholder=请输入链接').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', exposure_link)  # 输入链接
#             creative_view_tab.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()=保存').parent(2).click(by_js=True)  # 保存链接
#         else:
#             add_monitor_link_repeat(creative_view_tab, monitor_link, exposure_link)
#
#
#     # 行业资质编辑按钮
#     creative_view_tab.ele('tag:span@@class=link-text@@text()=编辑').wait(.5).click(by_js=True)
#
#     if creative_view_tab.ele('tag:button@@text()=继续修改', timeout=2):
#         logger.info("投放资质存在继续修改按钮")
#         creative_view_tab.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()=继续修改').click(by_js=True)
#         # edit_button.click(by_js=True) # 点击继续修改
#
#     # 选中行业资质具体内容
#     if indus_qualification_content_ele := creative_view_tab.ele(f'tag:div@@class=d-grid d-option d-option-content --color-text-title@@text():{indus_qualification}', timeout=2):
#         indus_qualification_content_ele.run_js('this.click();')
#     else: # 否则默认选中第一个
#         creative_view_tab.ele('css:.d-options-wrapper > .d-grid  > .d-grid-item:nth-child(1)', timeout=2).wait.displayed()
#         creative_view_tab.ele('css:.d-options-wrapper > .d-grid  > .d-grid-item:nth-child(1)', timeout=2).run_js('this.click();')
#
#     creative_view_tab.ele('tag:span@@text()= 绑定至当前创意 ').click(by_js=True) # 点击绑定当前创意
#
#     creative_view_tab.wait(1)
#     creative_view_tab.ele('tag:span@@text()=创意素材').scroll.to_center()
#
#     # 创意素材
#     if img_all_select == '否':
#         if creative_view_tab.ele('tag:a@@text()=添加封面', timeout=2):
#             creative_view_tab.ele('tag:a@@text()=添加封面').scroll.to_center()
#             creative_view_tab.ele('tag:a@@text()=添加封面').click(by_js=True)
#
#         if creative_view_tab.ele('tag:a@@text()=选择封面', timeout=2):
#             creative_view_tab.ele('tag:a@@text()=选择封面').scroll.to_center()
#             creative_view_tab.ele('tag:a@@text()=选择封面').click(by_js=True)
#
#         creative_view_tab.wait(1)
#         img_all_select_eles = creative_view_tab.eles('css:.modal-content-right > .select-photo-item')
#
#         if len(img_all_select_eles) > 1:
#             # creative_view_tab.wait.eles_loaded('tag:span@@text()=全选')
#             creative_view_tab.ele('tag:span@@text()=全选').click(by_js=True)
#             time.sleep(1)
#             creative_view_tab.ele('tag:span@@text()= 确认选择 ').click(by_js=True)
#         else:
#             creative_view_tab.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()= 取消 ').click(by_js=True)
#
#     creative_view_tab.ele(f'tag:div@@class=flexible align-center@@text()={auto_optimize}').click(by_js=True) # 自动优化
#
#     creative_view_tab.ele(f'tag:span@@text()={trans_comp}').scroll.to_center()  # 滚到转化组件
#     creative_view_tab.ele(f'tag:span@@text()={trans_comp}').parent(1).click(by_js=True) # 点击转化组件
#
#     if trans_comp == '搜索组件':
#         creative_view_tab.ele('tag:span@@text()=图片或视频底部').scroll.to_center()
#         img_or_video_ele = creative_view_tab.ele('tag:span@@text()=图片或视频底部')
#         img_or_video_ele_str = img_or_video_ele.prev().prev().attr('class')
#         if 'unchecked' not in img_or_video_ele_str:
#             img_or_video_ele.parent(1).click(by_js=True)  # 先取消图片或视频底部默认选中
#
#         top_comment_ele = creative_view_tab.ele('tag:span@@text()=置顶评论')
#         top_comment_ele_str = top_comment_ele.prev().prev().attr('class')
#         if 'unchecked' not in top_comment_ele_str:
#             top_comment_ele.parent(1).click(by_js=True)  # 先取消置顶评论默认选中
#
#         df_search_comp = get_search_comp(file_path)
#
#         if creative_name not in df_search_comp['创意名称'].tolist():
#             log_message(log_callback, f"当前计划的创意名称:{creative_name}在搜索组件sheet页中不存在, 可以前往当前创意界面手动输入", "red")
#             return
#
#         if not df_search_comp.empty:
#             for s in df_search_comp.itertuples():
#                 if creative_name != s.创意名称:
#                     continue
#                 comp_loc_arr = s.组件位置.split('\n')  ## 组件位置
#                 for comp in comp_loc_arr:
#                     if comp == '图片或视频底部':
#                         creative_view_tab.ele('tag:span@@text()=图片或视频底部').parent(1).wait(0.5).click(by_js=True) # 点击图片或视频底部
#                         creative_view_tab.ele('tag:input@@class=d-text@@type=text@@placeholder=请输入搜索词').input(s.搜索词, clear=True)  # 点击图片或视频底部
#                     if comp == '置顶评论':
#                         creative_view_tab.ele('tag:span@@text()=置顶评论').parent(1).wait(0.5).click(by_js=True)  # 点击置顶评论
#                         creative_view_tab.ele('css:.conversion-group > .input > .comment-input-box input[placeholder="请输入置顶评论文案"]').input(s.置顶评论文案, clear=True)  # 点击图片或视频底部
#                 break
#
#     creative_view_tab.ele('css:.footer-action .d-button:nth-child(2)').click(by_js=True)  # 点击创意层级完成
#     if not creative_view_tab.ele('tag:span@@class=error@@text():请选择组件的位置', timeout=1) and not creative_view_tab.ele('tag:span@@class=error@@text():请填写搜索词', timeout=1) and not creative_view_tab.ele('tag:span@@class=error@@text():请输入评论文案，默认项为必填', timeout=1):
#         browser.close_tabs(creative_view_tab)
#         logger.info(f"创意完成")


# 改造成循环的形式
def create_creative_func(creative_view_tab, r_excel, browser, file_path, log_callback=None, df_sheet=None, note_dict=None):
    # 根据excel填写的转化组件，查询对应sheet页的内容
    time.sleep(3)
    df_search_comp = get_search_comp(file_path=file_path, sheet_name="创意信息")

    if not df_search_comp.empty:
        items = creative_view_tab.eles('css:.d-tabs-headers-wrapper > div > div')
        # creative_view_tab.ele('@text()=创意2').run_js('this.click();')
        for i, item in enumerate(items):
            creative_view_tab.ele('tag:div@@class=d-space d-space-horizontal d-space-align-start d-tabs-headers d-tabs-headers-linear-top').scroll.to_center()
            time.sleep(2)
            # c_name = item.ele('tag:span@@class=d-text --color-static --color-text-title --size-text-paragraph bold d-text-nowrap d-text-ellipsis note-title').text
            creative_view_tab.ele('tag:div@@class=d-space d-space-horizontal d-space-align-start d-tabs-headers d-tabs-headers-linear-top').child(index=(i+1)).run_js('this.click();')
            time.sleep(1.5)

            current_creative_item = creative_view_tab.eles('css:#creativity .creativity-tab-container ~ div').filter_one.displayed()

            current_creative_item('tag:span@@class=form-item-label-text@@text()=创意名称').scroll.to_center()
            title_name = current_creative_item('tag:a@@class$promotion-note-content-info-title').text if current_creative_item('tag:a@@class$promotion-note-content-info-title').text else current_creative_item('tag:span@@class$promotion-note-content-info-desc').text

            for d in df_search_comp.itertuples():
                current_sheet_note_id = d.笔记ID
                if pd.notna(current_sheet_note_id):
                    current_sheet_note_id = current_sheet_note_id.strip()
                    if current_sheet_note_id != note_dict.get(title_name, ""):
                        continue

                    # 创意名称
                    func_creative_handle(d, df_search_comp, current_creative_item, title_name)
                    # 封面
                    fund_cover_handle(creative_view_tab, d, df_search_comp, current_creative_item)

                    time.sleep(1)
                    # 自动优化
                    func_auto_opitimize(d, df_search_comp, current_creative_item)
                    ## 处理转化组件
                    func_trans_comp_handle(current_creative_item, d, df_search_comp)
                    ## 监测链接
                    func_monitor_link_hand(creative_view_tab, d, df_search_comp, current_creative_item)

                    break
        # 第一个标签页编辑投放资质之后绑定至所有创意
        # if i == 0:
        #     handle_qualification(creative_view_tab, item, df_search_comp, current_note_id, comp_sheet_note_ids_arr, log_callback)
        # 应用至所有创意
        # if creative_view_tab.ele('tag:span@@text()= 应用至所有创意 ', timeout=1):
        #     creative_view_tab.ele('tag:span@@text()= 应用至所有创意 ', timeout=1).click(by_js=True)  # 点击应用至所有创意
        #     time.sleep(1)
        #     if creative_view_tab.ele('tag:p@@text()=部分创意当前已绑定资质，确认要修改资质吗？修改后会使创意重新送审并可能造成驳回，请谨慎修改。', timeout=1):
        #         creative_view_tab.ele('tag:span@@class=d-text --color-static --color-current --size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()=确认修改', timeout=1).parent(2).click(by_js=True)  # 点击确认修改
        #         time.sleep(1)
        #         handle_finishi_button(browser, creative_view_tab) # 点击创意界面完成按钮
        #         return

    # 点击创意界面完成按钮
    handle_finishi_button(browser, creative_view_tab)


def func_monitor_link_hand(creative_view_tab, d, df_search_comp, current_creative_item):
    required_columns = ['监测链接', '曝光链接']
    monitor_link = None
    exposure_link = None
    if any(col in df_search_comp.columns for col in required_columns):
        if '监测链接' in df_search_comp.columns:
            monitor_link = d.监测链接
            if pd.notna(monitor_link):
                monitor_link = monitor_link.strip()

        if '曝光链接' in df_search_comp.columns:
            exposure_link = d.曝光链接
            if pd.notna(exposure_link):
                exposure_link = exposure_link.strip()
        add_monitor_link_repeat_item(creative_view_tab, monitor_link=monitor_link, exposure_link=exposure_link, current_creative_item=current_creative_item)


def func_trans_comp_handle(creative_view_tab, d, df_search_comp):
    if '转化组件' in df_search_comp.columns:
        current_excel_trans_comp = d.转化组件

        if pd.isna(current_excel_trans_comp):
            current_excel_trans_comp = "无"
        current_excel_trans_comp = current_excel_trans_comp.strip()
        if creative_view_tab(f'tag:div@@class=flexible align-center@@text()={current_excel_trans_comp}', timeout=2):
            creative_view_tab(f'tag:div@@class=flexible align-center@@text()={current_excel_trans_comp}').scroll.to_center()
            creative_view_tab(f'tag:div@@class=flexible align-center@@text()={current_excel_trans_comp}').parent(3).click(by_js=True)  # 点击转化组件

        time.sleep(1)

        if current_excel_trans_comp == '搜索组件':
            search_comp_situation(creative_view_tab, d)
        if current_excel_trans_comp == '私信组件':
            message_comp_situation(creative_view_tab, d, creative_view_tab)


def func_auto_opitimize(d, df_search_comp, item):
    if '自动优化' in df_search_comp.columns:
        auto_distribute = d.自动优化
        auto_optimize(auto_distribute, item)


def fund_cover_handle(creative_view_tab, d, df_search_comp, current_creative_item):
    if '封面全选' in df_search_comp.columns:
        if d.封面全选 == '否':
            creative_material(creative_view_tab, current_creative_item)

def func_creative_handle(d, df_search_comp, item, title_name):
    if '创意名称' in df_search_comp.columns:
        excel_creative_name = d.创意名称
        if pd.notna(excel_creative_name):
            item.ele('tag:input@@placeholder=请输入创意名称').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', excel_creative_name)  # 填写创意名称
    else:
        item.ele('tag:input@@placeholder=请输入创意名称').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', title_name)  # 填写创意名称


def auto_optimize(auto_distribute, item):
    if pd.isna(auto_distribute):
        auto_distribute = "关闭"
    if item('tag:span@@class=form-item-label-text@@text()=自动优化', timeout=1):
        item('tag:span@@class=form-item-label-text@@text()=自动优化').scroll.to_center()
        item(f'tag:div@@class=flexible align-center@@text()={auto_distribute}').parent(3).click(by_js=True)  # 自动优化
    else:
        item(f'tag:div@@class=flexible align-center@@text()=关闭').parent(3).click(by_js=True)

def message_comp_situation(item, s, creative_view_tab):
    item('tag:span@@text()=置顶评论文案').scroll.to_center()
    if comp_title_ele := item.ele('tag:span@@text()=组件标题'):
        if comp_title_ele.parent(1).states.is_displayed:
            comp_title_ele.parent(1).next().child().child().child().input(s.组件标题, clear=True)

    clear_selected_option(item, option_text='互动栏胶囊')  # 清空
    clear_selected_option(item, option_text='置顶评论')  # 清空
    comp_loc_arr = s.组件位置.strip().split('\n')  ## 组件位置
    for comp in comp_loc_arr:
        comp = comp.strip()
        if comp == '互动栏胶囊':
            item(f'tag:span@@text()={comp}').parent(1).click(by_js=True)  # 互动栏胶囊
            show_people_num = s.组件展示已转化人数 if pd.notna(s.组件展示已转化人数) else '是'
            if show_people_num != '是':
                item('tag:div@@text()= 组件展示已转化人数 ').parent(1).next().child().child(index=-1).click(by_js=True)  # 点击不展示已转化人数
        if comp == '置顶评论':
            item(f'tag:span@@text()={comp}').parent(1).click(by_js=True)  # 点击置顶评论
            time.sleep(0.5)
            if item('css:.conversion-group > .input > .comment-input-box input[placeholder="请输入置顶评论文案"]', timeout=1):
                item('css:.conversion-group > .input > .comment-input-box input[placeholder="请输入置顶评论文案"]').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', s.置顶评论文案)  # 点击图片或视频底部

    # 选中组件按钮文案
    comp_button_str_handle(creative_view_tab, item)


def comp_button_str_handle(creative_view_tab, item):
    item('tag:span@@text()=组件按钮文案').scroll.to_center()
    item('tag:span@@text()=组件按钮文案').parent(1).next().child().child().run_js(mock_click_js)  # 组件按钮文案
    creative_view_tab.wait.eles_loaded('css:.d-new-cascader__option-list__item:nth-child(1) .d-new-cascader__column .d-new-cascader__option-wrapper')  # 等待元素加载
    # 先清空所有选项
    options = creative_view_tab.eles('css:.d-new-cascader__option-list__item:nth-child(1) .d-new-cascader__column .d-new-cascader__option-wrapper')
    for option in options:
        clickable_ele = option.child().child().child()
        status_class = clickable_ele.child().attr('class')
        if 'unchecked' not in status_class and 'indeterminate' not in status_class:
            clickable_ele.run_js(mock_click_js)  # 点击选项
        if 'indeterminate' in status_class:
            clickable_ele.run_js(mock_click_js)  # 点击选项
            clickable_ele.run_js(mock_click_js)  # 点击选项
    # 选中对应选项
    if button_text_str_ele := creative_view_tab.ele('tag:span@@class=d-text --color-static --color-text-paragraph --size-text-paragraph d-text-nowrap@@text()=通用文案'):
        comment_text_class = button_text_str_ele.parent(1).prev().child().child().attr('class')
        button_option_ele = button_text_str_ele.parent(1).prev().child()
        if 'unchecked' in comment_text_class:
            button_option_ele.run_js(mock_click_js)  # 点击通用文案
        if 'indeterminate' in comment_text_class:
            button_option_ele.run_js(mock_click_js)  # 点击通用文案
            button_option_ele.run_js(mock_click_js)  # 点击通用文案
            button_option_ele.run_js(mock_click_js)  # 点击通用文案


def handle_finishi_button(browser, creative_view_tab):
    creative_view_tab.ele('tag:span@@class=d-text --color-static --color-current --size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()= 开始投放 ').parent(2).click(by_js=True)  # 点击创意层级完成

    if (
            not creative_view_tab.ele('tag:span@@class=error@@text():请选择组件位置', timeout=0.5)
            and not creative_view_tab.ele('tag:span@@class=error@@text():请填写搜索词', timeout=0.5)
            and not creative_view_tab.ele('tag:span@@class=error@@text():单元名称重复', timeout=0.5)
            and not creative_view_tab.ele('tag:span@@class=error@@text():计划名称重复', timeout=1)
            and not creative_view_tab.ele('tag:span@@class=error@@text():请输入评论文案，默认项为必填', timeout=1)
            and not creative_view_tab.ele('tag:span@@class=d-text --color-static --color-text-paragraph --size-text-paragraph@@text()=请输入标题', timeout=1)
    ):
        browser.close_tabs(creative_view_tab)
        logger.info(f"创意完成")


def clear_selected_option(item, option_text='互动栏胶囊'):
    item_capsule_class = item(f'tag:span@@text()={option_text}').prev().prev().attr('class')
    if 'unchecked' not in item_capsule_class and 'disabled' not in item_capsule_class:
        item(f'tag:span@@text()={option_text}').parent(1).click(by_js=True)  # 互动栏胶囊

def search_comp_situation(item, s):
    item('tag:span@@class=checkbox-label@@text()=图片或视频底部').scroll.to_center()
    img_or_video_ele = item('tag:span@@class=checkbox-label@@text()=图片或视频底部')
    img_or_video_ele_str = img_or_video_ele.parent(1).prev().prev().attr('class')
    if 'unchecked' not in img_or_video_ele_str:
        img_or_video_ele.parent(2).click(by_js=True)  # 先取消图片或视频底部默认选中
    top_comment_ele = item('tag:span@@class=checkbox-label@@text()=置顶评论')
    top_comment_ele_str = top_comment_ele.parent(1).prev().prev().attr('class')
    if 'unchecked' not in top_comment_ele_str:
        top_comment_ele.parent(2).click(by_js=True)  # 先取消置顶评论默认选中

    search_word = s.搜索词 if s.搜索词 else ""
    comp_loc_arr = s.组件位置.strip().split('\n')  ## 组件位置
    for comp in comp_loc_arr:
        comp = comp.strip()
        if comp == '图片或视频底部':
            img_or_video_ele.parent(2).click(by_js=True)  # 点击图片或视频底部
            time.sleep(0.3)
            item('tag:input@@class=d-text@@type=text@@placeholder=请输入搜索词').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', search_word)  # 输入搜索词
        if comp == '置顶评论':
            top_comment_ele.parent(2).click(by_js=True)  # 点击置顶评论
            time.sleep(0.3)
            item('tag:input@@class=d-text@@placeholder=请输入置顶评论文案').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', s.置顶评论文案)
            item('tag:input@@class=d-text@@type=text@@placeholder=请输入搜索词').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', search_word)


def creative_material(creative_view_tab, current_creative_item):
    if current_creative_item('tag:a@@text()= 添加封面 ', timeout=1):
        current_creative_item('tag:a@@text()= 添加封面 ').scroll.to_center()
        current_creative_item('tag:a@@text()= 添加封面 ').click(by_js=True)
    else:
        if current_creative_item('tag:a@@text()= 选择封面 ', timeout=1):
            current_creative_item('tag:a@@text()= 选择封面 ').scroll.to_center()
            current_creative_item('tag:a@@text()= 选择封面 ').click(by_js=True)
    time.sleep(1)

    img_all_select_left_eles = creative_view_tab.eles('css:.modal-content-left-covers > .photo-item')
    img_all_select_right_eles = creative_view_tab.eles('css:.modal-content-right > .select-photo-item')

    if len(img_all_select_left_eles) == len(img_all_select_right_eles):
        # creative_view_tab.wait.eles_loaded('tag:span@@text()=全选')
        creative_view_tab.ele('tag:span@@text()=全选').click(by_js=True)
        time.sleep(1)
        creative_view_tab.ele('tag:span@@text()= 确认选择 ').click(by_js=True)
    else:
        if len(img_all_select_right_eles) > 1:
            creative_view_tab.ele('tag:span@@text()=全选').click(by_js=True)
            creative_view_tab.ele('tag:span@@text()=全选').click(by_js=True)
            creative_view_tab.ele('tag:span@@text()= 确认选择 ').click(by_js=True)
        else:
            creative_view_tab.ele('tag:span@@class=d-text --color-static --color-current --size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()= 确认选择 ').parent(2).click(by_js=True)


def handle_qualification(creative_view_tab, item, df_search_comp, current_note_id, comp_sheet_note_ids_arr, log_callback):
    if current_note_id not in comp_sheet_note_ids_arr:
        log_message(log_callback=log_callback, message=f'当前笔记ID{current_note_id}在副页【创意信息】sheet表格中不存在,默认使用副页中第一条笔记的选项信息', color="purple")
        first_row = next(df_search_comp.itertuples())
        qualification_name_handle(creative_view_tab, item, first_row)
    else:
        for dd in df_search_comp.itertuples():
            if pd.isna(dd.笔记ID):
                continue
            if current_note_id != dd.笔记ID.strip():
                continue
            qualification_name_handle(creative_view_tab, item, dd)
            break


def qualification_name_handle(creative_view_tab, item, current_row):
    indus_qualification = current_row.行业资质
    item('tag:span@@class=link-text@@text()=编辑').wait(.5).click(by_js=True)
    if creative_view_tab.ele('tag:button@@text()=继续修改', timeout=2):
        logger.info("投放资质存在继续修改按钮")
        creative_view_tab.ele('tag:button@@text()=继续修改', timeout=2).click(by_js=True)
    # 选中行业资质具体内容
    if indus_qualification_content_ele := creative_view_tab.ele(f'tag:div@@class=d-grid d-option d-option-content --color-text-title@@text():{indus_qualification.strip()}', timeout=2):
        indus_qualification_content_ele.run_js('this.click()')  # 选中具体资质内容
    else:
        creative_view_tab.ele('css:.d-options-wrapper > .d-grid  > .d-grid-item:nth-child(1)', timeout=2).wait.displayed()
        creative_view_tab.ele('css:.d-options-wrapper > .d-grid  > .d-grid-item:nth-child(1)', timeout=2).run_js('this.click()')
    if all_bind_ele := creative_view_tab.ele('tag:span@@text()= 绑定至所有创意 ', timeout=1):  # 点击绑定当前创意
        all_bind_ele.parent(2).wait.enabled()
        all_bind_ele.parent(2).click(by_js=True)  # 点击绑定所有创意
        time.sleep(1.5)
    elif current_bind_ele := creative_view_tab.ele('tag:span@@text()= 绑定至当前创意 ', timeout=1):
        current_bind_ele.parent(2).wait.enabled()
        current_bind_ele.parent(2).click(by_js=True)  # 点击绑定当前创意
    else:
        creative_view_tab.ele('tag:span@@text()= 取消 ', timeout=1).click(by_js=True)
    if creative_view_tab.ele('tag:button@@text()=确认修改', timeout=2):
        logger.info("投放资质存在确认修改按钮")
        creative_view_tab.ele('tag:button@@text()=确认修改', timeout=2).click(by_js=True)


def add_monitor_link_repeat(creative_view_tab, monitor_link, exposure_link):
    if add_monitor_link := creative_view_tab.ele('tag:div@@text()=添加监测链接', timeout=3):
        add_monitor_link.click(by_js=True, timeout=3)  # 点击添加监测链接
        creative_view_tab.wait(1)

        if pd.notna(monitor_link):
            monitor_link_arr = monitor_link.strip().split('\n')
            for monitor in monitor_link_arr:
                creative_view_tab.ele('tag:span@@text()=点击监测链接').next().ele('tag:span@@class=add-action@@text()= 添加 ').click(by_js=True, timeout=3)  # 点击添加
                creative_view_tab.ele('tag:div@@class=err-tips@@text()=请输入监测链接').wait.displayed()
                creative_view_tab.ele('tag:div@@class=err-tips@@text()=请输入监测链接').prev().ele('tag:input@@class=d-text@@placeholder=请输入链接').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', monitor)  # 输入链接

        if pd.notna(exposure_link):
            exposure_link_arr = exposure_link.strip().split('\n')
            for exposure in exposure_link_arr:
                creative_view_tab.ele('tag:span@@text()=曝光监测链接').next().ele('tag:span@@class=add-action@@text()= 添加 ').click(by_js=True, timeout=3)  # 点击添加
                creative_view_tab.ele('tag:div@@class=err-tips@@text()=请输入监测链接').wait.displayed()
                creative_view_tab.ele('tag:div@@class=err-tips@@text()=请输入监测链接').prev().ele('tag:input@@class=d-text@@placeholder=请输入链接').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', exposure)  # 输入链接

        creative_view_tab.ele('tag:span@@class$--size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()=保存').parent(2).click(by_js=True)  # 保存链接


def add_monitor_link_repeat_item(creative_view_tab, monitor_link=None, exposure_link=None, current_creative_item=None):
    if add_monitor_link := current_creative_item('tag:span@@class=d-text --color-static --color-current --size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()=去配置', timeout=1.5):
        add_monitor_link.parent(2).click(by_js=True)  # 去配置
        time.sleep(1)

        if pd.notna(monitor_link):
            monitor_link_arr = monitor_link.strip().split('\n')
            if monitor_link_add_ele := creative_view_tab.ele('tag:span@@text()=点击监测链接', timeout=2):
                for monitor in monitor_link_arr:
                    monitor_link_add_ele.next().ele('tag:span@@class=add-action@@text()= 添加 ', timeout=3).click(by_js=True)  # 点击添加
                    creative_view_tab.ele('tag:span@@class^d-text --color-static --color-text-paragraph --size-text-paragraph@@text()=请输入监测链接').wait.displayed()
                    creative_view_tab.ele('tag:span@@class^d-text --color-static --color-text-paragraph --size-text-paragraph@@text()=请输入监测链接').prev().ele('tag:input@@class=d-text@@placeholder=请输入链接').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', monitor)

        if pd.notna(exposure_link):
            exposure_link_arr = exposure_link.strip().split('\n')
            if exposure_link_add_ele := creative_view_tab.ele('tag:span@@text()=曝光监测链接', timeout=2):
                for exposure in exposure_link_arr:
                    exposure_link_add_ele.next().ele('tag:span@@class=add-action@@text()= 添加 ', timeout=3).click(by_js=True)  # 点击添加
                    creative_view_tab.ele('tag:span@@class^d-text --color-static --color-text-paragraph --size-text-paragraph@@text()=请输入监测链接').wait.displayed()
                    creative_view_tab.ele('tag:span@@class^d-text --color-static --color-text-paragraph --size-text-paragraph@@text()=请输入监测链接').prev().ele('tag:input@@class=d-text@@placeholder=请输入链接').run_js('this.value = arguments[0]; this.dispatchEvent(new Event("input"));', exposure)  # 输入链接

        creative_view_tab.ele('tag:span@@class=d-text --color-static --color-current --size-text-paragraph d-text-nowrap d-text-ellipsis d-text-nowrap@@text()=保存').parent(2).click(by_js=True)  # 保存链接
        time.sleep(1)

# if __name__ == '__main__':
#     file_path = r"D:\Users\Desktop\信息流-创建计划-美团医美测试1.xlsx"
#
#     browser = Chromium()  ## 临时测试、到时候删掉， 只保留调用create_unit()函数
#     unit_view_tab = browser.latest_tab  ## 临时测试、到时候删掉
#     unit_view_tab.get('https://ad.xiaohongshu.com/aurora/ad/create2?from=CampaignList&vSellerId=64dc2da17db5df00019f10e5')  ## 临时测试、到时候删掉
#
#     sheet1_data = get_complete_sheet1(file_path)
#     for index, row in sheet1_data.iterrows():
#         if index == 0:
#             create_creative_func(unit_view_tab, row, browser, file_path, df_sheet=sheet1_data)
